package org.dromara.web.listener;

import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.ip.IpParameters;
import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Getter
public class AutoCloseableModbusMaster implements AutoCloseable {

    private static final Logger log = LoggerFactory.getLogger(AutoCloseableModbusMaster.class);

    private final ModbusMaster modbusMaster;

    public AutoCloseableModbusMaster(String host, int port) throws ModbusInitException {
        ModbusFactory modbusFactory = new ModbusFactory();
        IpParameters params = new IpParameters();
        params.setHost(host);
        params.setPort(port);

        ModbusMaster master = null;
        try {
            master = modbusFactory.createTcpMaster(params, false);
            master.init();
            log.info("ModbusMaster initialized successfully for host: {}, port: {}", host, port);
        } catch (ModbusInitException e) {
            log.error("Failed to initialize ModbusMaster for host: {}, port: {}", host, port, e);
            throw e; // Rethrow the exception to notify caller of failure
        }
        this.modbusMaster = master;
    }

    /**
     * Close the ModbusMaster connection safely
     */
    @Override
    public void close() {
        if (modbusMaster != null) {
            try {
                modbusMaster.destroy();
                log.info("ModbusMaster connection closed successfully.");
            } catch (Exception e) {
                log.error("Error occurred while closing ModbusMaster connection.", e);
            }
        } else {
            log.warn("Attempted to close a null ModbusMaster connection.");
        }
    }
}
